package com.deying.httplockserver.utils;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.deying.httplockserver.core.HttpLockRequest;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.AttributeKey;

/**
 * netty http  帮助
 * @author jjliu
 *
 */
public class NettyHttpUtils {
	static byte[] DATA_SUCCESS;
	static byte[] DATA_ERROR_TRY;
	static byte[] DATA_ERROR_TRY_TIMEOUT;
	static byte[] DATA_ERROR_URL;
	static byte[] DATA_ERROR_TID;
	static byte[] DATA_ERROR_NOLOCK;
	static{
		try {
			DATA_SUCCESS = "成功".getBytes("utf-8");
			DATA_ERROR_TRY = "试图锁定失败".getBytes("utf-8");
			DATA_ERROR_TRY_TIMEOUT = "试图锁定超时".getBytes("utf-8");
			DATA_ERROR_URL = "错误的地址".getBytes("utf-8");
			DATA_ERROR_TID = "错误的TID".getBytes("utf-8");
			DATA_ERROR_NOLOCK = "没有此锁".getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	
	public static void sendResponse(ChannelHandlerContext ctx,HttpResponseStatus httpResponseStatus ,byte[] contentData){
		if(ctx.channel().isActive()){
			FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus,Unpooled.wrappedBuffer(contentData));
			response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
			response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
			response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE);
			response.headers().set("Access-Control-Allow-Origin", "*");            
			response.headers().set("Access-Control-Allow-Methods", "*");            
			response.headers().set("Access-Control-Allow-Headers", "Content-Type");
			ctx.write(response);
			ctx.flush();
		}
	}

	public static void sendSuccess(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.OK,DATA_SUCCESS);
	}
	
	public static void sendErrorMessage(ChannelHandlerContext ctx,byte[] errorData){
		sendResponse(ctx,HttpResponseStatus.INTERNAL_SERVER_ERROR,errorData);
	}
	
	public static void sendErrorMessage(ChannelHandlerContext ctx,String error){
		try {
			sendResponse(ctx,HttpResponseStatus.INTERNAL_SERVER_ERROR,error.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	public static void sendErrorTry(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.CONFLICT,DATA_ERROR_TRY);
	}
	public static void sendErrorTryTimeout(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.CONFLICT,DATA_ERROR_TRY_TIMEOUT);
	}
	public static void sendErrorUrl(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.BAD_REQUEST,DATA_ERROR_URL);
	}
	public static void sendErrorTid(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.NOT_ACCEPTABLE,DATA_ERROR_TID);
	}
	public static void sendErrorNoLock(ChannelHandlerContext ctx){
		sendResponse(ctx,HttpResponseStatus.NOT_FOUND,DATA_ERROR_NOLOCK);
	}

	///////////////////////////////////////////////////
	
	
	public static String getParamString(Map<String, List<String>> params,String name){
		return getParamString(params,name,null);
	}
	public static String getParamString(Map<String, List<String>> params,String name,String defaultValue){
		List<String> valueList =  params.get(name);
		String res = null;
		if(valueList!=null && valueList.size()>0){
			res = valueList.get(0);
			if(StringUtils.isBlank(res)){
				res = null;
			}
		}
		if(res==null){
			return defaultValue;
		}else{
			return res;
		}
	}
	public static Integer getParamInteger(Map<String, List<String>> params,String name){
		return getParamInteger(params,name,null);
	}
	public static Integer getParamInteger(Map<String, List<String>> params,String name,Integer defaultValue){
		String str = getParamString(params,name,null);
		Integer res=null;
		if(str!=null){
			res =  Integer.parseInt(str);
		}
		if(res==null){
			return defaultValue;
		}else{
			return res;
		}
	}
	public static Boolean getParamBoolean(Map<String, List<String>> params,String name){
		return getParamBoolean(params,name,null);
	}
	public static Boolean getParamBoolean(Map<String, List<String>> params,String name,Boolean defaultValue){
		String str = getParamString(params,name,null);
		Boolean res=null;
		if(str!=null){
			res =  Boolean.parseBoolean(str);
		}
		if(res==null){
			return defaultValue;
		}else{
			return res;
		}
	}
	
	public static void markCtxBlockHttpLockRequest(HttpLockRequest httpLockRequest){
		httpLockRequest.getCtx().channel().attr(AttributeKey.valueOf(HttpLockRequest.class.getSimpleName())).set(httpLockRequest);
	}
	
	public static void unMarkCtxBlockHttpLockRequest(HttpLockRequest httpLockRequest){
		httpLockRequest.getCtx().channel().attr(AttributeKey.valueOf(HttpLockRequest.class.getSimpleName())).set(null);
	}

	public static HttpLockRequest getMarkCtxBlockHttpLockRequest(ChannelHandlerContext ctx){
		return ctx.channel().attr(AttributeKey.<HttpLockRequest>valueOf(HttpLockRequest.class.getSimpleName())).get();
	}

}
